package com.zuorenke.vertx.handler;


import com.zuorenke.help.HandlerUtils;
import com.zuorenke.help.ResponseUtils;
import com.zuorenke.model.constants.Constants;
import com.zuorenke.model.Performer;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;


/**
 * @author Z.R.K
 * @description
 * @create 2019-05-10 16:09:25
 **/
@Component
@Slf4j
public class RequestBusinessHandler implements Handler<RoutingContext> {
	
	@Override
	public void handle(RoutingContext event) {
		Performer performer = event.get(Constants.ROUTE_PERFORMER);
		Object[] params = event.get(Constants.ROUTE_PARAMS);
		try {
			Object result;
			if (params != null) {
				result = performer.getMethod().invoke(performer.getBean(), params);
			} else {
				result = performer.getMethod().invoke(performer.getBean());
			}
			event.put(Constants.WEB_DATA, result);
			HandlerUtils.next(event);
		} catch (IllegalAccessException e) {
			log.error("IllegalAccessException {}", e);
			ResponseUtils.responseErrorMsg(event.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
		} catch (InvocationTargetException e) {
			log.error("InvocationTargetException {}", e);
			ResponseUtils.responseErrorMsg(event.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
		}
	}
}
